import xlwt
from xmindparser import xmind_to_dict
import time
import re


class XmindToexcel:
    # 读取xmind文件方法
    def __init__(self, name):
        try:
            self.xmind_dict = xmind_to_dict(name)[0]['topic']
            # print('读取了文件')
            # print(self.xmind_dict)
        except Exception as e:
            print(f'未找到xmind文件：{e}')
        # 创建excel和命名sheet
        self.work = xlwt.Workbook(encoding='utf-8')
        self.sheet = self.work.add_sheet('测试用例', cell_overwrite_ok=True)
    # 字典转列表

    @staticmethod
    def infinite_for(self, loop, case, case_list):
        for branches in loop:
            # 定义新字符串，把所有路径加起来
            strvar = case + branches['title'] + '/#'
            # print(branches['title'])
            # print(strvar)
            # ****把读取完单分支添加到列表
            if 'topics' not in branches:
                case_list.append(strvar)
                continue
            # print(f'这是总列表：{case_list}')
            # 通过topics嵌套读取字典首个title
            branch = branches['topics']
            # print(branch)
            # # 无限循环调用方法，遍历他的全部分支
            self.infinite_for(self, branch, strvar, case_list)
    # 保存excel文件

    @staticmethod  # 静态方法，直接使用不需要实例化
    def xmind_makers(value):
        return value["makers"][0]

    @staticmethod
    def save_excel(self):
        path = '.\\'
        t = str(time.time())[:9]
        self.work.save(path + self.xmind_dict['title'] + t + '.xls')
        print(f'excel输出文件路径为：{path}')
    # 列表数据写入excel

    def excel_write(self):
        # 设置标头
        # print('执行了写入')
        head = ['所属产品', '关键词', '相关研发需求', '用例名称',
                '步骤', '预期', '所属模块', '优先级', '适用阶段', '用例类型']
        '''
        禅道填写说明：
        用例类型:功能测试 性能测试 配置相关 安装部署 安全相关 接口测试 单元测试 其他
        优先级:1 2 3 4 -
        适用阶段:单元测试阶段 功能测试阶段 集成测试阶段 系统测试阶段 冒烟测试阶段 版本验证阶段
        '''
        for i in head:
            self.sheet.write(0, head.index(i), i)
        loop = self.xmind_dict['topics']
        # print(loop)
        case = ''
        case_list = []
        self.infinite_for(self, loop, case, case_list)
        # print(case_list)
        # 写入excel行数n
        n = 1
        global l_var
        try:
            # 所属产品
            sysName = self.xmind_dict['title']
            # 关键词 + 需求 加号分割
            vandq = re.split('\+', loop[0]['title'], )
            if vandq is not None:
                # print(vandq)
                version = vandq[0]
                request = vandq[1]
            else:
                version = ''#未匹配到版本号为空
                request = ''#未匹配到需求为空
            # print(version + request)
            for var in case_list:
                var1 = var.split('/#')[:-1]
                # print(var1)
                # 所属模块
                model = var1[1:2]
                # print(model)
                # 预期结果
                result = var1[-1]
                # print(result)
                # 预期结果
                step = var1[-2]
                # print(step)
                # 步骤
                title1 = '-'.join(var1[1:-2])
                # 标题
                # print(title1)
                l_var = [sysName, version, request,
                         title1, step, result, model]
                for i in range(len(l_var)):
                    # print(i)
                    self.sheet.write(n, i, l_var[i])
                    # 优先级
                    if 'priority-1' in title1:
                        self.sheet.write(n, 7, '1')  # 优先级
                    # elif 'priority-3' in self.xmind_makers(self.xmind_dict['topics'][0]):
                    #     self.sheet.write(n, 6, '低')  # 优先级
                    # # 适用阶段
                    # elif '冒烟用例' in self.xmind_makers(self.xmind_dict['topics'][0]):
                    #     self.sheet.write(n, 7, '冒烟用例')  # 适用阶段
                    # 默认值
                    else:
                        self.sheet.write(n, 7, '3')  # 优先级，默认3-中
                        self.sheet.write(n, 8, '功能测试阶段')  # 适用阶段，默认：功能测试阶段
                        self.sheet.write(n, 9, '功能测试')  # 用例类型，默认：功能测试

                # 行数自增
                n += 1
        except Exception as e:
            print(f'数据格式不符合规则：{e}')
        self.save_excel(self)
